import axios from 'axios'
import store from '@/store/index'
//创建axios实例
const request = axios.create({
    //请求公共部分
    baseURL: 'http://localhost:8880',
    //超时时间
    timeout: 10000,
    //设置请求头
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
    },
});
//配置拦截器

//请求拦截器
request.interceptors.request.use(function (config) {
    //注册时请求头带上用户名，处理重复提交的请求
    if (config.url.includes('/indexUser/register') || config.url.includes('/indexUser/resetPassword')) {
        config.headers['username'] = config.data.username;
    }
    //把token和username放进请求头中，每次请求都要带上token验证
    if (store.state.user.token) {
        config.headers['Authorization'] = store.state.user.token;
        config.headers['username'] = store.state.user.username;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
})
//响应拦截器
request.interceptors.response.use(function (result) {
//处理错误响应
    if (result.data.code === 20040) {
        return Promise.reject(result);
    } else {
        return Promise.resolve(result);
    }

})

export default request;